package com.wn.budget.service.admin;

import com.wn.budget.code.context.ContextManager;
import com.wn.budget.model.Admin;
import com.wn.budget.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class AdminService {

    @Autowired
    AdminRepository adminRepository;

    public Admin login(HttpServletRequest request, String account, String password) {

        Admin admin = adminRepository.findByAccount(account);
        if (admin == null) {
            throw new RuntimeException("用户不存在。");
        }
        if (!admin.account.equals(account) || !admin.password.equals(password)) {
            throw new RuntimeException("用户名或密码错误。");
        }

        admin.password = null;
        ContextManager.setLoginUser(request, admin);
        return admin;
    }

    public boolean logout(HttpServletRequest request) {
        return ContextManager.logout(request);
    }
}
